package com.wh.minihelp.filter.impl;

import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class LocalFunctionContext extends FunctionContext {
	// private static final String URL = "jdbc:mysql://127.0.0.1:3306/wh_flowers";
	// private static final String USERNAME = "root";
	// private static final String PASSWORD = "root";

	private static final String URL = "jdbc:mysql://127.0.0.1:3306/wh_flowers?useUnicode=true&characterEncoding=utf8";
	private static final String USERNAME = "root";
	private static final String PASSWORD = "root";

	// private static final String URL = "jdbc:mysql://192.168.128.133:3306/wh_flowers?useUnicode=true&characterEncoding=utf8";
	// private static final String USERNAME = "root";
	// private static final String PASSWORD = "root";

	// 获取数据数据库连接
	public Connection createConnection() throws SQLException, InstantiationException, IllegalAccessException, ClassNotFoundException {
		Class.forName(DRIVER).newInstance();// 每次都作此测试，否则有时会出现类加载不上的情况
		Connection cnn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
		cnn.setAutoCommit(false);
		return cnn;
	}

	@Override
	public String getTmpPath() {
		// 本地放到res目录下，主要是为了方便从外部访问
		String tmp = getRequest().getSession().getServletContext().getRealPath("res/tmp");
		File tmpDir = new File(tmp);
		if (!tmpDir.exists()) {
			tmpDir.mkdirs();
		}
		try {
			return tmpDir.getCanonicalPath();
		} catch (IOException e) {
			return tmpDir.getAbsolutePath();
		}
	}

	@Override
	public String uploadFile(String tmpFile, String storeFile) {
		return "/res/tmp/" + new File(tmpFile).getName();// 本地的话这里可以搞简单点
		// FileInputStream fin = null;
		// FileOutputStream fos = null;
		// byte[] buffer = new byte[1024];
		// try {
		// fin = new FileInputStream(tmpFile);
		// String tmp = getRequest().getSession().getServletContext().getRealPath("res/tmp");
		// File f = new File(tmp, storeFile);
		// fos = new FileOutputStream(f);
		// while (fin.read(buffer) != -1) {
		// fos.write(buffer);
		// }
		// } catch (IOException e) {
		// if (LogUtil.rootLog.isErrorEnabled()) LogUtil.rootLog.error("上传文件出错！", e);
		// throw new LogicException("上传文件出错！", e);
		// } finally {
		// if (fos != null) try {
		// fos.close();
		// } catch (IOException e) {}
		// if (fin != null) try {
		// fin.close();
		// } catch (IOException e) {}
		// }
		// return "/res/tmp/" + storeFile.replace('\\', '/');
	}
}
